<template>
    <div>
        <el-form :model="contributeForm" :rules="rules" ref="contributeForm">
        <el-form-item label="类别" :label-width="formLabelWidth" prop="module">
          <el-select v-model="contributeForm.module">
            <el-option v-for="(item,index) in moduleOption" :key="index" :label="item.name" :value="item.avdRelId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model.trim="contributeForm.title"></el-input>
        </el-form-item>
        <el-form-item label="分类" :label-width="formLabelWidth" prop="typeIds">
          <el-select v-model="contributeForm.typeIds">
            <el-option v-for="(item,index) in typeOption" :key="index" :label="item.name" :value="item.avdRelId"></el-option>
          </el-select>
          <el-input class="inputcontent" type="textarea" placeholder="请输入内容" v-model.trim="contributeForm.description">
          </el-input>
        </el-form-item>
        <el-form-item label="标签" :label-width="formLabelWidth" prop="tagIds">
          <el-select v-model="contributeForm.tagIds">
            <el-option v-for="(item,index) in tagOption" :key="index" :label="item.name" :value="item.avdRelId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" :label-width="formLabelWidth" prop="brandIds">
          <el-select v-model="contributeForm.brandIds">
            <el-option v-for="item in brandOption" :key="item.avdRelId" :label="item.name" :value="item.avdRelId"></el-option>
          </el-select>
        </el-form-item>
          <wangEditor ref="child" v-model="contributeForm.paragraph"  @change="change"></wangEditor>
        <el-form-item label="封面设置" :label-width="formLabelWidth" class="imgmar" prop="cover">
          <el-upload :action="upload_file_url" :headers="upHeaders" accept="image/*" :limit="1" :on-change="handleLimit" :class="{disabled:eqObj.uploadDisabled}" list-type="picture-card" :on-success="handleSuccess"  :on-remove="handleRemove" :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body width="52%">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
         <el-form-item label="上传视频" :label-width="formLabelWidth" class="imgmar upload-images" prop="video">
          <el-upload :action="upload_vedio_url" accept="video/*" :headers="upHeaders"  :limit="1" :before-upload="handleVideoupload" :on-change="handleLimitvideo"  :class="{disabled:eqObj.uploadVideo}" list-type="picture-card" :on-success="handleSuccessvideo" :on-remove="handleRemovevideo" :on-preview="handleVideoPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
        <el-dialog :visible.sync="dialogvideoVisible" append-to-body width="52%">
          <video-player  class="video-player vjs-custom-skin" ref="videoPlayer"
            :playsinline="true"
            :options="playerOptions">
          </video-player>
        </el-dialog>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="promise">承诺图片，字体，视频，内容不可侵犯</el-checkbox>
          <el-checkbox v-model="agree">同意《远大支持论坛投稿协议》</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="goKeep('contributeForm')">保存草稿</el-button>
        <el-button type="primary" @click="goExamine('contributeForm')">提交审核</el-button>
        <el-button @click="goWatch()" icon="el-icon-view">
           预览
        </el-button>
      </div>
    </div>
</template>
<script>
import $ from 'jquery'
import wangEditor from './wangEditor.vue';
import{ getActicleSave,getGuidesuccess,getActicleoption,deleteImgList,deleteVideoList } from './../api/guide'
import { getToken } from "@/utils/token.js";
export default {
    components: { wangEditor },
    data(){
        return{
            brandOption:[],
            moduleOption:[],
            tagOption:[],
            promise:false,
            agree:false,
            dialogVisible: false,
            disabled: false,
            dialogvideoVisible:false,
            typeOption:[],
            eqObj:{
            uploadDisabled:false,
            uploadVideo:false,
            },
            dialogImageUrl: '',
            upload_file_url: process.env.VUE_APP_URL + '/api/v1/file/uploadImage?category=cover', // 图片上传地址
            upload_vedio_url:process.env.VUE_APP_URL + '/api/v1/file/uploadVideo?category=video', //视频上传地址
            upHeaders:{
            'Authorization':"6a77998089b8467d83d2094a8011b02d",
            'Token':'Bearer '+ getToken()
            },
            videoUrl:'',
            contributeForm: {
            module: '',
            title: '',
            typeIds:[],
            description: '',
            tagIds: [],
            brandIds:[],
            paragraph:'',
            cover: '',
            video:'',
            },
            rules:{
            module:[
                {required:true, message: '请选择类别', trigger: 'blur'}
            ],
            title:[
                {required:true, message: '请输入标题', trigger: 'blur'}
            ],
            typeIds:[
                {required:true, message: '请选择分类', trigger: 'blur'},
            ],
            description:[
                {required:true, message: '请输入内容', trigger: 'blur'}
            ],
            tagIds:[
                {required:true, message: '请输入标签', trigger: 'blur'}
            ],

            cover: [
                { required: true, message: '请上传图片', trigger: "change" }
            ],
            video:[
                {required:true, message: '请上传视频', trigger: 'change'}
            ],
            },
            playerOptions : {
                playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
                autoplay: false, // 如果true,浏览器准备好时开始回放。
                muted: false, // 默认情况下将会消除任何音频。
                loop: false, // 导致视频一结束就重新开始。
                preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
                language: 'zh-CN',
                aspectRatio: '15:6', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
                fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
                sources: [],
                poster: "", // 封面地址
                notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
                controlBar: {
                timeDivider: true, // 时间分割线
                durationDisplay: true, // 总时间
                remainingTimeDisplay: true, // 剩余播放时间
                progressControl: true, // 进度条 
                fullscreenToggle: true  // 全屏按钮
                }
            },
            formLabelWidth: '120px'
        }
    },
    methods:{
        handleLimit(file, fileList) {
        if (fileList.length >= 1) {
            this.eqObj.uploadDisabled = true;
            this.$set(this.eqObj, 'uploadDisabled', true);
        } else {
            this.eqObj.uploadDisabled = false;
            this.$set(this.eqObj, 'uploadDisabled', false);
        }
      },
      handleSuccess(response, file, fileList) {
        if (response.code == 200) {
          this.contributeForm.cover=response.result.relativeUrl;
          this.$message.success("上传成功");
          this.$refs.contributeForm.validateField('cover');
        }else{
          this.$message.error('视频上传失败，请重新上传！');
        }
      },
      handlePictureCardPreview(file){
        if(file.response.code == 200){
          this.dialogImageUrl = file.response.result.absoluteUrl;
          this.dialogVisible = true;
        }
      },
      handleRemove(file) {
        if(file.response.code == 200){
          console.log(file.response.result.relativeUrl);
          deleteImgList(file.response.result.relativeUrl).then(res=>{
            console.log(res,'删除图片');
            // this.eqObj.uploadDisabled = false;
          })
        }
        this.eqObj.uploadDisabled = false;
      },
      handleLimitvideo(file, fileList) {
        console.log(file, fileList,'2222222222222')
        if (fileList.length >= 1) {
            this.eqObj.uploadVideo = true;
            this.$set(this.eqObj, 'disabledvideo', true);
        } else {
            this.eqObj.uploadVideo = false;
            this.$set(this.eqObj, 'disabledvideo', false);
        }
      },
      handleVideoupload(file){
        console.log(file,'33333333333');
      },
      handleSuccessvideo(response, file, fileList) {
        // console.log(response,'22222222222');
        $('.upload-images .el-upload--picture-card').hide();
        $('.upload-images .el-upload--picture-card').hide();
        $('.upload-images .el-upload-list .el-upload-list__item').prepend('<video></video>');
        $('.upload-images .el-upload-list .el-upload-list__item video').addClass('el-upload-list__item-thumbnail');
        $('.upload-images .el-upload-list .el-upload-list__item video').attr({
            width: '320px',
            height: '240px',
            controls: 'controls',
            src: file.url
        });
        // $('.upload-images .el-upload-list .el-upload-list__item img').remove();
        if (response.code == 200) {
          this.contributeForm.video = response.result.relativeUrl;
          this.$message.success("上传成功");
        }else{
          this.$message.error('视频上传失败，请重新上传！');
        }
      },
      handleVideoPreview(file){
        console.log(file,'223333333333');
        if(file.response.code == 200){
          this.videoUrl = file.response.result.absoluteUrl;
          this.dialogvideoVisible = true;
          this.playerOptions.sources.push(this.videoUrl);
        }
      },
      handleRemovevideo(file, fileList) {
        console.log(file, fileList);
        if(file.response.code == 200){
          console.log(file.response.result.relativeUrl);
          deleteVideoList({relativePath:file.response.result.relativeUrl}).then(res=>{
            console.log(res,'删除视频');
          })
        }
        
        this.eqObj.uploadVideo = false;
        $('.upload-images .el-upload--picture-card').show();

      },
      change(data){
        this.contributeForm.paragraph = data;
      },
      // 保存草稿
      goKeep(formName){
        let params = {
          isDraft:true,
          typeIds:[this.$refs[formName].model.typeIds],
          brandIds:[this.$refs[formName].model.brandIds],
          tagIds:[this.$refs[formName].model.tagIds],
          module: this.$refs[formName].model.module,
          title: this.$refs[formName].model.title,
          description: this.$refs[formName].model.description,
          paragraph: this.$refs[formName].model.paragraph,
          cover: this.$refs[formName].model.cover,
          video: this.$refs[formName].model.video,
        }
        getActicleSave(params).then(res=>{
          console.log(res)
          if(res.code == 200){
            this.$message.success("保存成功");
          }
        })
      },
      // 提交审核
      goExamine(formName){
        if(!getToken()){
          this.$message.warning('请您先登录，再提交')
        }else{
          if(this.agree && this.promise ){
            this.$refs[formName].validate((valid) => {
              if (valid) {
                let params = {
                  isDraft: false,
                  typeIds:[this.$refs[formName].model.typeIds],
                  brandIds:[this.$refs[formName].model.brandIds],
                  tagIds:[this.$refs[formName].model.tagIds],
                  module: this.$refs[formName].model.module,
                  title: this.$refs[formName].model.title,
                  description: this.$refs[formName].model.description,
                  paragraph: this.$refs[formName].model.paragraph,
                  cover: this.$refs[formName].model.cover,
                  video: this.$refs[formName].model.video,
                }
                // console.log(params);
                getActicleSave(params).then(res=>{
                  console.log(res)
                  if(res.code == 200){
                    this.$message.success("提交成功");
                    this.dialogFormVisible = false;
                    let obj = {
                      'avdId':0,
                    };
                    obj.avdId = res.result.avdId;
                    getGuidesuccess(obj).then(res=>{
                      console.log(res)
                    })
                    // this.$refs['contributeForm'].resetFields()
                  }
                })
              }else{
                return false; 
              }
            })
          }else{
            this.$message.error('请同意远大支持论坛投稿协议并承诺图片，字体，视频，内容不可侵犯');
            return false;
          }

        }
       
      },
      // 预览
      goWatch(){
        // 通过代码获取编辑器内容
        let data = this.contributeForm.paragraph;
        console.log(data);
        this.$router.push({
          name:'preview',
          params:{
            data
          }
        })
      },
    },
    created(){
        getActicleoption().then(res=>{
            this.typeOption = res.result.typeOptions;
            console.log(this.typeOption,'数据');
            this.brandOption = res.result.brandOptions;
            this.moduleOption = res.result.moduleOptions;
            this.tagOption = res.result.tagOptions;
        })
        // 列表
        // this.listParams.typeIds.push(parseInt(this.active_Warp))
    }
}
</script>
<style lang="less" scoped>
@import './../assets/style/edit.css';
    .el-form{
      padding:0 5%;
    }
    .el-select{
      width: 100%;
    }
    .inputcontent{
      margin-top: 10px;
    }
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 146px;
    text-align: center;
    border: 1px solid #ccc;
  }
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
  }
  .imgmar{
    margin-top: 40px;
  }
  .el-checkbox{
    display: block;
  }
  .dialog-footer{
    display: flex;
    justify-content: space-around;
    align-items: center;
    .el-button{
      display: block;
    }
  }
.disabled .el-upload{
    display: none !important;
}

.disabled .el-button--success.is-plain {
    display: none !important;
}
</style>